﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Controls.Maps;
using System.Device.Location;
using Microsoft.Phone.Tasks;
using System.Text;
using System.IO;
using System.Xml.Linq;
using System.Runtime.Serialization.Json;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using unifiqAnthony.AzureSvc;


namespace unifiqAnthony
{
    public partial class FriendsPage : PhoneApplicationPage
    {

        List<UFriend> friends = new List<UFriend>();
        List<ULocation> locations = new List<ULocation>();
        List<FriendDistance> FriendDistance = new List<FriendDistance>();

        public FriendsPage()
        {
            //load friends of user
            getFriends(App.LoginInfo.uid);
        }

        void FriendsPage_Loaded(object sender, RoutedEventArgs e)
        {
            List<FriendItem> friendList = new List<FriendItem>();
            String DefaultName = "Name";
            String DefaultDistance = "";
            String DefaultPic = "Images/profile0";

                for (int i = 1; i < friends.Count + 1; i++)
                {
                    if (App.LoginInfo.uid == 1)
                    {
                        if (i == 1)
                        {
                            DefaultName = "John";
                            //set picture
                            DefaultPic = DefaultPic + i.ToString() + ".png";
                        }
                        else
                        {
                            DefaultName = "Anthony";
                            DefaultPic = "Images/profile02.png";
                        }
                    }
                    else
                    {
                        if (i == 1)
                        {
                            DefaultName = "Jane";
                            DefaultPic = "Images/profile03.png";
                        }
                        else
                        {
                            DefaultName = "Anthony";
                            DefaultPic = "Images/profile02.png";
                        }
                    }
                    //calculate distance of location to friend
                    DefaultDistance = Convert.ToInt32( GetDistanceBetweenPoints( locations.ElementAt(0).lat, locations.ElementAt(0).longit, locations.ElementAt(i) ) ).ToString() + " metres";
                    friendList.Add(new FriendItem(DefaultName, DefaultDistance, DefaultPic));
                }
            FriendList.ItemsSource = friendList;
        }

        //get friend distances
        void friendDistances()
        {

            getCurrentDistance(1);
            foreach (UFriend uf in friends)
            {
                getCurrentDistance(uf.f2);
            }

        }

        //get distance from azure
        private void getCurrentDistance(int uid)
        {
            AzureSvc.Service1Client client = new AzureSvc.Service1Client();
            client.getLatestLocAsync(uid);
            client.getLatestLocCompleted += new EventHandler<AzureSvc.getLatestLocCompletedEventArgs>(client_getLatestLocCompleted);
 
        }

        private void client_getLatestLocCompleted(object sender, AzureSvc.getLatestLocCompletedEventArgs e)
        {
            locations.Add(e.Result);

            if (locations.Count == (friends.Count + 1) )
            {
                InitializeComponent();
                Loaded += new RoutedEventHandler(FriendsPage_Loaded);
            }
        }
        
        //get friends from azure
        private void getFriends(int uid)
        {
            AzureSvc.Service1Client client = new AzureSvc.Service1Client();
            client.getFriendsAsync(uid);
            client.getFriendsCompleted += new EventHandler<AzureSvc.getFriendsCompletedEventArgs>(client_getFriends);
        }

        private void client_getFriends(object sender, AzureSvc.getFriendsCompletedEventArgs e)
        {
            friends = e.Result.ToList();
            friendDistances();
        }

        //method to calculate distance between current location and each friend
        public double GetDistanceBetweenPoints(double currentLat, double currentLong, AzureSvc.ULocation friendLocation)
        {
            double lat2 = friendLocation.lat;
            double long2 = friendLocation.longit;
            double distance = 0;
            double dLat = (lat2 - currentLat) / 180 * Math.PI;
            double dLong = (long2 - currentLong) / 180 * Math.PI;
            double a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2)
            + Math.Cos(lat2) * Math.Sin(dLong / 2) * Math.Sin(dLong / 2);
            double c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            //Calculate radius of earth
            // assume any of the two points.
            double radiusE = 6378135; // Equatorial radius, in metres
            double radiusP = 6356750; // Polar Radius
            //Numerator part of function
            double nr = Math.Pow(radiusE * radiusP * Math.Cos(currentLat / 180 * Math.PI), 2);
            //Denominator part of the function
            double dr = Math.Pow(radiusE * Math.Cos(currentLat / 180 * Math.PI), 2)
            + Math.Pow(radiusP * Math.Sin(currentLat / 180 * Math.PI), 2);
            double radius = Math.Sqrt(nr / dr);
            //Calaculate distance in metres.
            distance = radius * c;
            return distance;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //get selected friend
            var selectedFriend = ((Button)sender).DataContext as FriendItem;
            //store selected friend in session
            App.SelectedFriend.friendSelected = selectedFriend;
            //navigate to friend location
            NavigationService.Navigate(new Uri("/FriendLocation.xaml", UriKind.Relative));
        }

}
}